﻿using Dapper;
using InventoryIssue.API.Read.Application.Command.Reportloss;
using InventoryIssue.Dtos;
using InventoryIssue.ErrorCode;
using InventoryIssue.Infrastructrue.Implement;
using MediatR;
using System.Text;

namespace InventoryIssue.API.Read.Application.Handler.Reportloss
{
    public class GetReportlossProductHandler : IRequestHandler<GetReportlossProductCommand, APIResult<List<ReportlossProductDto>>>
    {
        private readonly DatabaseContext db;

        public GetReportlossProductHandler(DatabaseContext db)
        {
            this.db = db;
        }
        public async Task<APIResult<List<ReportlossProductDto>>> Handle(GetReportlossProductCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<ReportlossProductDto>> result = new APIResult<List<ReportlossProductDto>>();
            StringBuilder sql = new StringBuilder();
            sql.Append(@"SELECT
	                        a.productId,
	                        a.productName,
	                        a.productCode,
	                        a.Specifications,
                            a.Price,
	                        b.LocationName,
	                        c.ReportlossId,
	                        c.Id,
	                        d.UnitName 
                        FROM
	                        productmodel a
	                        JOIN locationmodel b ON a.LocationId = b.LocationId
	                        JOIN reportlossproductmodel c ON a.ProductId = c.ProductId
	                        JOIN unitmodel d ON a.UnitId = d.UnitId 
                        WHERE
	                        a.IsDel = 0 
	                        AND b.IsDel = 0 
	                        AND c.IsDel = 0 
	                        AND d.IsDel = 0 
	                        AND c.ReportlossId = @ReportlossId;"
            );
            var parameters = new
            {
                ReportlossId = request.ReportlossId
            };
            var data = await db.DapperConnection.QueryAsync<ReportlossProductDto>(sql.ToString(), parameters);
            result.Message = "显示成功";
            result.Code = APIEnum.Ok;
            result.Data = data.ToList();
            return result;
        }
    }
}
